<?php

namespace Service;

use Core\Di;
/**
 * Yar服务
 * Class YarService
 * @package Service
 */
class YarService
{
    /**
     * yar token
     * @var
     */
    protected static $token = '';

    public static function getToken()
    {
        if( empty(self::$token) ){
            $params = [
                "iss" => "https://www.mutouyun.com",
                "aud" => 'RPC',
                "exp" => time() + 600,//120
            ];
            $key = Di::get('config')['secretKey']['rpcPrivateKey'];

            $token = JwtService::encode($params, $key, 'RS256');
            self::$token = $token;
        }
        return self::$token;
    }
    public static function create($uri, $target, $params = [], $platform = 2)
    {
        try{
            $yarClient = new \Yar_Client(RPC_URL . $uri);
            $yarReturn = $yarClient->index($target, $params, $platform, self::getToken());
            // 统一RPC的返回
            $ret =  [
                'code' => $yarReturn['code'],
                'msg' =>  $yarReturn['msg'],
                'debugMsg' => $yarReturn['debugMsg'],
                'data' => $yarReturn['data']
            ];
            if (!empty($yarReturn['url'])){
                $ret['code'] = 1;
                $ret['url'] = $yarReturn['url'];
                $ret['params'] = $yarReturn['params'];
            }
            if(!empty($yarReturn['HTurl'])){
                $ret['HTurl'] = $yarReturn['HTurl'];
            }
            return $ret;
        }catch (\Exception $e) {
            return [
                'code'  => 5000,
                'msg'   => $e->getMessage() . '(' .$e->getCode() . ')',
                'debugMsg' => $e->getMessage() . '(' .$e->getCode() . ')'
            ];
        }
    }
}